package com.qu.waibao.network;

import com.qu.waibao.utils.GsonUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/28.
 */

public class HttpParamsUtil {
    public static String getVars(Map<String, String> map){

        return getUrlParamsByMap(map);
    }

    /**
     * map转成url
     *
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, String> map) {
        if (map == null) {
            return "";
        }

        return GsonUtil.mapToJson(map);
    }

    /**
     * map升序转成url
     *
     * @param map
     * @param isSort true为升序，false为map顺序
     * @return
     */
    public static String getUrlParams(Map<String, String> map, boolean isSort) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        List<String> keys = new ArrayList<String>(map.keySet());
        if (isSort) Collections.sort(keys);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = map.get(key).toString();
            sb.append(key + "=" + value);
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.lastIndexOf("&"));
        }
        return s;
    }

}
